# -*- coding: utf-8 -*-
# @name             : 请求封装
# @author           : OneYoung
# @create           : 2024/07/18
# @version          : v1.0
# @desc             : 封装 HTTP 请求方法

from requests import Session
from application.settings import *


class Request:

    def __init__(self):
        # 定义接口请求参数
        self.timeout = TIMEOUT
        self.headers = HEADERS
        self.params = {}
        self.data = {}
        self.json = {}
        self.url = ''
        self.files = None
        self.cookies = ''

    def set_url(self, url: str):
        """
        配置API地址

        :param url: 接口地址
        """
        self.url = BASE_URL + url

    def set_header(self, header: dict):
        """
        配置请求头

        :param header: 请求头对象
        """
        for key, value in header.items():
            self.headers[key] = value

    def add_token(self, token: str):
        """
        添加授权token

        :param token: 授权token
        """
        self.headers['Authorization'] = f"Bearer {token}"

    def set_params(self, param: dict):
        """
        配置params入参

        :param param: params入参
        """
        self.params = param

    def set_data(self, data: dict):
        """
        配置data入参

        :param data: body入参
        """
        self.data = data

    def set_json(self, json_data: dict):
        """
        配置json入参

        :param json_data: json请求入参
        """
        self.json = json_data

    def set_files(self, file: str):
        """
        配置上传文件

        :param file: 上传文件路径
        """
        self.files = file

    def set_timeout(self, timeout: int):
        """
        配置超时时间

        :param timeout: 超时时间(s),需大于1s
        """
        self.timeout = timeout

    def set_cookies(self, cookies: dict):
        """
        配置cookies

        :param cookies: cookies对象
        """
        self.cookies = cookies

    def base_request(self, method, **kwargs):
        """
        基本请求信息
        :param method: 请求方法，GET/POST/PUT/DELETE...
        :param kwargs: 请求参数，与session.request一致
        """
        session = Session()
        # 请求参数
        request_params = {
            "url": self.url,
            "params": self.params,
            "data": self.data,
            "json": self.json,
            "headers": self.headers,
            "cookies": self.cookies,
            "files": self.files,
            "timeout": float(self.timeout)
        }
        request_params.update(**kwargs)
        return session.request(method, **request_params)

    def get(self):
        """GET请求方法"""
        return self.base_request('GET')

    def post(self):
        """POST请求方法"""
        return self.base_request('POST')

    def put(self):
        """PUT请求方法"""
        return self.base_request('PUT')

    def patch(self):
        """PATCH请求方法"""
        return self.base_request('PATCH')

    def delete(self):
        """DELETE请求方法"""
        return self.base_request('DELETE')
